package com.heima.se.sjms.工厂.spring的bean工厂;

/*
    面试题：手写一个Spring IOC 容器。
    IOC思想：对象不要自己new，统一交给spring帮你创建，你要就找spring去拿。

    IOC容器：本质是一个集合，用来装对象的。
 */

import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class BeanFactory {

    public static Map<String,Object> springIOC;
    static {
        //1. 实例化ioc容器
        springIOC = new HashMap<>();
        try {
            //2. 开始装载bean
            //2.1 扫描bean: 读取配置文件信息
            //使用Properties读取application.properties配置信息到内存
            Properties properties = new Properties();
            FileReader fr = new FileReader("D:\\IdeaProjects\\heima-leadnews\\heima-leadnews-test\\javaSE-demo\\src\\main\\resources\\application.properties");
            properties.load(fr);
            fr.close();

            //2.2 开始bean的实例化
            Set<Object> keys = properties.keySet();
            for (Object beanName : keys) {
                String className = properties.getProperty(String.valueOf(beanName));
                Object bean = Class.forName(className).newInstance();

                //3. 完成bean的装载，实现IOC容器的初始化
                springIOC.put(String.valueOf(beanName),bean);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Object getBean(String beanName){
        return springIOC.get(beanName);
    }


    public static void main(String[] args) {
        Object studentDao = BeanFactory.getBean("studentDao");
        System.out.println("studentDao = " + studentDao);

        Object studentService = BeanFactory.getBean("studentService");
        System.out.println("studentService = " + studentService);
    }
}

